package com.rp.api.interceptors;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.rp.news.common.ResponseStatusEnum;
import com.rp.news.enums.UserStatus;
import com.rp.news.exception.GraceException;
import com.rp.news.util.RedisOperator;
import com.rp.pojo.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserActivityInterceptor extends BaseInterceptor implements HandlerInterceptor {


    @Autowired
    public RedisOperator redis;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String userId = request.getHeader("headerUserId");

        String s = redis.get(REDIS_USER_INFO + ":" + userId);
        AppUser appUser = null;
        if(StrUtil.isNotBlank(s)){
            appUser = JSONUtil.toBean(s, AppUser.class);
        }else {

            GraceException.display(ResponseStatusEnum.UN_LOGIN);
        }

        if(appUser.getActiveStatus() == null|| appUser.getActiveStatus() != UserStatus.ACTIVE.type){
            GraceException.display(ResponseStatusEnum.USER_INACTIVE_ERROR);
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
